package org.jground.rx.ui.zk.docu;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.dbfs.IDBFile;
import org.jground.dbfs.IDBFileService;
import org.jground.rx.RXLangStrings;
import org.jground.rx.RXSystem;
import org.jground.rx.ui.zk.UIStyles;
import org.jground.zk.zulX.HboxX;
import org.zkoss.image.AImage;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Html;
import org.zkoss.zul.Image;
import org.zkoss.zul.Popup;

public class UIImageView extends HboxX implements EventListener {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Log logger = LogFactory.getLog(UIAttributeViewDocu.class);

    private static RXLangStrings openWithOriginalSize = new RXLangStrings();
    static {
        openWithOriginalSize.setDefault("Open with original size : ");
        openWithOriginalSize.add("en", "Open with original size : ");
        openWithOriginalSize.add("de", "In Originalgrösse öffnen : ");
    }

    private Popup popup = new Popup();
    private Image displayImage = new Image();
    private Button fullscreenButton = new Button();

    public UIImageView() {
        //
        fullscreenButton.setImageContent(UIStyles.getInstance().getAImage(UIStyles.ImageKey.fullscreen16));
        fullscreenButton.addEventListener(Events.ON_CLICK, this);
        add(fullscreenButton);
        //
        add(popup);
        displayImage.setParent(popup);
        displayImage.addEventListener(Events.ON_CLICK, this);
        //

    }

    public void setAImageFile(IDBFile file) {
        try {
        	IDBFileService fs = RXSystem.getInstance().getFileService();
            displayImage.setContent(new AImage(file.getName(), fs.getData(file)));
            fullscreenButton.setTooltiptext(openWithOriginalSize + FilenameUtils.getName(file.getName()));
        } catch (Exception e) {
            Html html = new Html("Could not open image! ");
            html.setParent(popup);
            logger.error(e, e);
        }
    }

    public void onEvent(Event event) throws Exception {
        if (event.getTarget() == displayImage) {
            popup.close();
        } else if (event.getTarget() == fullscreenButton) {
            popup.open(fullscreenButton);
        }
    }

}
